package com.bodacn.keypoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;


public class FragmentA extends Fragment implements View.OnClickListener {
    public static String TAG=FragmentA.class.getName();
    public static final int msgFocusBarcode = 1001;
    public static final int MSG_SCANBARCODE = 9001;
    public static final int MSG_DETAIL = 9002;
    public static final int MSG_CUTLIST = 9003;
    public static final int MSG_SEARCHOVER = 9004;
    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    //全局变量
    Toast curToast;
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,CPUID;
    Button btn_CutQuery,btn_PullAdd,btn_PullEdit,btn_SearchSelect;
    EditText edt_SearchStyleNo;
    ListView markListView,cutListView;
    TextView txt_HintInfo,txt_OrderNo,txt_StyleNo,txt_StyleSort;
    JSONArray headJSON,detailJSON,cutlistJson,orderJSON;
    JSONObject titleInfo;
    TextView itemSize1,itemSize2,itemSize3,itemSize4,itemSize5,itemSize6,itemSize7,itemSize8,itemSize9,itemSize10,itemSize11,itemSize12,itemSize13,itemSize14,itemSize15;
    String curProduceCutMaID,curProduceMasterID,curMakeState;//裁床ID,马克ID
    LinearLayout templetlisthead;
    ListView selectTempletList;
    String selOrderNo="",selStyleNo="",selStyleSort="";
    private ProgressDialog waitDialog = null;
    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    public FragmentA() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerA(new MainActivity.OnTransParamsListenerA() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d(this.getClass().getName(),"LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curServiceDir=mParams.get("ServiceDir").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            CPUID=mParams.get("CPUID").toString();
                            Log.d(this.getClass().getName(),"LoginParam------------------>2");
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }



    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                //消息处理;
                System.out.println("收到的消息是："+msg.what);
                int msgId = msg.what;
                switch (msgId) {
                    case MSG_SEARCHOVER:
                        showSelectOrder();
                        break;
                    case MSG_DETAIL:
                        final DetailListAdapter detailListAdapter = new DetailListAdapter(getActivity());
                        markListView.setAdapter(detailListAdapter);
                        break;
                    case MSG_CUTLIST:
                        final CutListAdapter cutListAdapter = new CutListAdapter(getActivity());
                        cutListView.setAdapter(cutListAdapter);
                        break;
                    default:
                        break;
                }
            }
        }
    };


    //显示工序选择
    private void showSelectOrder(){
        if (orderJSON==null) {
            return;
        }
        try {
            headJSON=new JSONArray("[{\"TitleName\":\"StyleNo\",\"TitleText\":\"款号\",\"TxtSize\":18,\"TxtWidth\":150,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}," +
                    "{\"TitleName\":\"OrderNo\",\"TitleText\":\"制单号\",\"TxtSize\":18,\"TxtWidth\":150,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"StyleSort\",\"TitleText\":\"款式\",\"TxtSize\":18,\"TxtWidth\":100,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"CustName\",\"TitleText\":\"客户\",\"TxtSize\":18,\"TxtWidth\":200,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}]");


        } catch (JSONException e) {
            e.printStackTrace();
        }
        titleInfo=null;
        //创建布局
        String dgCaption="制单选择";
        LayoutInflater inflater=this.getLayoutInflater();
        final View selectTemplet=inflater.inflate(R.layout.select_templet, null);
        templetlisthead=selectTemplet.findViewById(R.id.templetlisthead);
        //创建表头;
        CreateListHead();
        detailJSON=orderJSON;
        //Activity.findViewById最终还是会调用View.findViewById
        selectTempletList=selectTemplet.findViewById(R.id.selectTempletList);
        selectTempletList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                view.setSelected(true);
                titleInfo=detailJSON.optJSONObject(position);
            }
        });
        //显示表明细
        SelectTempletListAdapter selectTempletListAdapter=new SelectTempletListAdapter(getContext());
        selectTempletList.setAdapter(selectTempletListAdapter);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(selectTemplet).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        if (titleInfo!=null) {
                            //填充并过滤
                            fillFormtext(titleInfo);
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, true);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        } else{
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, false);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText("请点击要选择的内容！");
                            curToast.show();

                        }
                    }

                }
        ).setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    selOrderNo="";
                    selStyleNo="";
                    selStyleSort="";
                    Field field = null;
                    field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
            }
        }).setTitle(dgCaption);
        final AlertDialog alterDialog =builder.create();
        alterDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //禁止两个按键上获取焦点，不然扫描框里就会失去焦点,在OnShow之前;
                System.out.println("alterDialog-setOnShowListener");
            }
        });
        alterDialog.show();
        //此处设置位置窗体大小
        WindowManager.LayoutParams params = alterDialog.getWindow().getAttributes();
        params.width = 800;
        params.height = 600 ;
        alterDialog.getWindow().setAttributes(params);
    }

    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }
    //创建列;
    private void CreateListHead() {
        //内容为表头，宽度，自适应;
        if ((headJSON != null) && (headJSON.length() > 0)) {
            int childCount = templetlisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = templetlisthead.getChildAt(i);
                if (view instanceof TextView) {
                    templetlisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            for (int i=0;i<headJSON.length();i++)
                if (headJSON.optJSONObject(i).has("TitleText") == true) {
                    try {
                        TitleName = headJSON.optJSONObject(i).getString("TitleName");
                        TitleText = headJSON.optJSONObject(i).getString("TitleText");
                        TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                        txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(getContext());
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.white));
                        tv.setTextSize(TxtSize);
                        if (headJSON.optJSONObject(i).has("Align")==true) {
                            Align = headJSON.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (headJSON.optJSONObject(i).has("Color")==true){
                            tv.setTextColor(GetColorValue( headJSON.optJSONObject(i).getString("Color")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) templetlisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else templetlisthead.addView(tv);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            templetlisthead.postInvalidate();
        }
    }


    //数据适配器，继承自BaseAdapter;
    private final class SelectTempletListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SelectTempletListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        public  String TrnasValue(String params)
        {
            if ((params.toUpperCase()=="NULL".toUpperCase())||(params=="0")||(params=="0.0"))
                return "";
            else return params;
        }
        @Override
        public int getCount() {
            //每页行数
            return detailJSON.length();
        }
        @Override
        public Object getItem(int position) {
            try {
                if (position<detailJSON.length())
                    return detailJSON.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.select_templet_item, null, false);
            //变换背景色
            /*
            if (position%2==1) {
                view.setBackgroundColor(getResources().getColor(R.color.content));
            }
            */
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,60));
            //转换分页码;
            int curPosition= position;
            String tmpValue;
            int color = getResources().getColor(R.color.text_black);
            if (curPosition<detailJSON.length()) {
                try {
                    Log.d(TAG, "getView()----------------------------------------------------->" + position);
                    if (detailJSON.optJSONObject(curPosition).has("ConColor") == true) {
                        tmpValue = detailJSON.optJSONObject(curPosition).getString("ConColor");
                        color=GetColorValue(tmpValue);
                    }
                    for (int i = 0; i < headJSON.length(); i++)
                        if (headJSON.optJSONObject(i).has("TitleText") == true) {
                            try {
                                String TitleName = headJSON.optJSONObject(i).getString("TitleName");
                                if (detailJSON.optJSONObject(curPosition).has(TitleName)==true) tmpValue= detailJSON.optJSONObject(curPosition).getString(TitleName);
                                else tmpValue="unReturn";
                                int TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                                float txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                                int AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                                TextView tv = new TextView(view.getContext());
                                tv.setText(TrnasValue(tmpValue));
                                tv.setWidth((int) txtWidth);
                                tv.setTextColor(color);
                                tv.setGravity(Gravity.CENTER_VERTICAL);
                                if (headJSON.optJSONObject(i).has("Align")==true) {
                                    int Align;
                                    Align = headJSON.optJSONObject(i).getInt("Align");
                                    switch (Align) {
                                        case 0:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                            break;
                                        case 1:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                            break;
                                        case 2:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                            break;
                                        default:
                                            tv.setGravity(Gravity.CENTER_VERTICAL);
                                            break;
                                    }
                                }
                                tv.setTextSize(TxtSize);
                                //添加到View中;
                                if (AutoZoom == 1)
                                    ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                                else ((LinearLayout)view).addView(tv);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
            return view;
        }
    }
    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getActivity().getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_a, container, false);
        InitView(root);
        System.out.println(this.getClass().getName()+"_onCreateView");
        return root;
    }
    //初始化;
    public void InitView(View view){
        //提示框pd=new ProgressDialog(this);
        waitDialog= new ProgressDialog(getContext());
        waitDialog.setTitle(getString(R.string.SystemHint));
        //界面控件;
        markListView= view.findViewById(R.id.markListView);
        markListView.setFocusable(false);
        markListView.setFocusableInTouchMode(false);
        markListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //获取ID
                showCutDetail(curProduceMasterID);
            }
        });
        cutListView= view.findViewById(R.id.cutListView);
        cutListView.setFocusable(false);
        cutListView.setFocusableInTouchMode(false);
        cutListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //获取ID
                if (cutlistJson.optJSONObject(position).has("ProduceCutMaID")==true)
                {
                    try {
                        curProduceCutMaID=cutlistJson.optJSONObject(position).getString("ProduceCutMaID");
                        if (cutlistJson.optJSONObject(position).has("MakeState")==true) curMakeState=cutlistJson.optJSONObject(position).getString("MakeState");
                        else curMakeState="";
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        btn_CutQuery=view.findViewById(R.id.btn_CutQuery);
        btn_CutQuery.setOnClickListener(this);
        btn_PullAdd=view.findViewById(R.id.btn_PullAdd);
        btn_PullAdd.setOnClickListener(this);
        btn_PullEdit=view.findViewById(R.id.btn_PullEdit);
        btn_PullEdit.setOnClickListener(this);
        edt_SearchStyleNo=view.findViewById(R.id.edt_SearchStyleNo);
        edt_SearchStyleNo.setOnClickListener(this);
        btn_SearchSelect=view.findViewById(R.id.btn_SearchSelect);
        btn_SearchSelect.setOnClickListener(this);
        txt_HintInfo=view.findViewById(R.id.txt_HintInfo);
        txt_OrderNo=view.findViewById(R.id.txt_OrderNo);
        txt_StyleNo=view.findViewById(R.id.txt_StyleNo);
        txt_StyleSort=view.findViewById(R.id.txt_StyleSort);
        //表格标题
        itemSize1=view.findViewById(R.id.txt_item_Size1);
        itemSize2=view.findViewById(R.id.txt_item_Size2);
        itemSize3=view.findViewById(R.id.txt_item_Size3);
        itemSize4=view.findViewById(R.id.txt_item_Size4);
        itemSize5=view.findViewById(R.id.txt_item_Size5);
        itemSize6=view.findViewById(R.id.txt_item_Size6);
        itemSize7=view.findViewById(R.id.txt_item_Size7);
        itemSize8=view.findViewById(R.id.txt_item_Size8);
        itemSize9=view.findViewById(R.id.txt_item_Size9);
        itemSize10=view.findViewById(R.id.txt_item_Size10);
        itemSize11=view.findViewById(R.id.txt_item_Size11);
        itemSize12=view.findViewById(R.id.txt_item_Size12);
        itemSize13=view.findViewById(R.id.txt_item_Size13);
        itemSize14=view.findViewById(R.id.txt_item_Size14);
        itemSize15=view.findViewById(R.id.txt_item_Size15);


        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);

    }


    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(getActivity(), notification);
        r.play();

    }


    //刷新缸布列表;
    private void queryDetailData(String paramProduceMasterID)
    {
        try {
            cutlistJson=new JSONArray("[]");
            //显示预排单;
            final CutListAdapter cutListAdapter = new CutListAdapter(getActivity());
            cutListView.setAdapter(cutListAdapter);
            detailJSON=new JSONArray("[]");
            final DetailListAdapter detailListAdapter = new DetailListAdapter(getActivity());
            markListView.setAdapter(detailListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm = "Exec KeyPoint_SearchStyleDe @ProduceMasterID='" + paramProduceMasterID+"',@OPERTYPE='DETAIL',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        ReadSQLData(SqlComm);
    }

    private void showCutDetail(String paramProduceMasterID){
        waitDialog.setTitle("获取床次清单..");
        curProduceCutMaID ="";
        //执行SQL过程
        String SqlComm = "Exec KeyPoint_GetCutList @ProduceMasterID='" + paramProduceMasterID+ "',@OPERTYPE='CUTLIST',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        ReadSQLData(SqlComm);

    }
    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }
    private void showIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.showSoftInput(edt, 0);
            }
        } catch (Exception e) {

        }
    }


    @Override
    public void onClick(View v) {
        hideIM(v);
        System.out.println(v);
        Bundle paramBundle = new Bundle();
        switch (v.getId()){
            case R.id.btn_SearchSelect:
                String searchStyleNo="";
                if ((edt_SearchStyleNo.getText()!=null)&&(edt_SearchStyleNo.getText().toString().length()>0)) searchStyleNo=edt_SearchStyleNo.getText().toString();
                searchStyleNoData(searchStyleNo);
                break;
            case R.id.btn_CutQuery:
                Intent intentCutQueryActivity=new Intent(getContext(),CutQueryActivity.class);
                //简单参数通过Intent的Extras传递;
                if((curProduceMasterID==null)||(curProduceMasterID.length()==0)) {
                    curToast.setText("请先搜索过滤出制单信息!");
                    curToast.show();
                    return;
                }
                paramBundle.clear();
                paramBundle.putString("LoginUserNo", curLoginUserNo);
                paramBundle.putString("LoginUser",curLoginUser);
                paramBundle.putString("CurDepartNo",curDepartNo);
                paramBundle.putString("CurDepart",curDepart);
                paramBundle.putString("ServiceUrl",curServiceUrl);
                paramBundle.putString("ServiceDir",curServiceDir);
                paramBundle.putString("CPUID",CPUID);
                paramBundle.putString("ProduceMasterID", curProduceMasterID);
                paramBundle.putString("OrderNo",txt_OrderNo.getText().toString());
                paramBundle.putString("StyleNo",txt_StyleNo.getText().toString());
                paramBundle.putString("StyleSort",txt_StyleSort.getText().toString());
                paramBundle.putString("Size1",itemSize1.getText().toString());
                paramBundle.putString("Size2",itemSize2.getText().toString());
                paramBundle.putString("Size3",itemSize3.getText().toString());
                paramBundle.putString("Size4",itemSize4.getText().toString());
                paramBundle.putString("Size5",itemSize5.getText().toString());
                paramBundle.putString("Size6",itemSize6.getText().toString());
                paramBundle.putString("Size7",itemSize7.getText().toString());
                paramBundle.putString("Size8",itemSize8.getText().toString());
                paramBundle.putString("Size9",itemSize9.getText().toString());
                paramBundle.putString("Size10",itemSize10.getText().toString());
                paramBundle.putString("Size11",itemSize11.getText().toString());
                paramBundle.putString("Size12",itemSize12.getText().toString());
                paramBundle.putString("Size13",itemSize13.getText().toString());
                paramBundle.putString("Size14",itemSize14.getText().toString());
                paramBundle.putString("Size15",itemSize15.getText().toString());
                intentCutQueryActivity.putExtras(paramBundle);
                startActivity(intentCutQueryActivity);
                break;
            case R.id.btn_PullAdd:
                hideIM(v);
                if ((detailJSON!=null)&&(detailJSON.length()>0)){
                    Intent intentPullActivity=new Intent(getContext(),PullActivity.class);
                    curProduceCutMaID = UUID.randomUUID().toString();
                    //简单参数通过Intent的Extras传递;
                    paramBundle.clear();
                    paramBundle.putString("LoginUserNo", curLoginUserNo);
                    paramBundle.putString("LoginUser",curLoginUser);
                    paramBundle.putString("CurDepartNo",curDepartNo);
                    paramBundle.putString("CurDepart",curDepart);
                    paramBundle.putString("ServiceUrl",curServiceUrl);
                    paramBundle.putString("ServiceDir",curServiceDir);
                    paramBundle.putString("CPUID",CPUID);
                    paramBundle.putString("ProduceCutMaID", curProduceCutMaID);
                    paramBundle.putString("ProduceMasterID", curProduceMasterID);
                    paramBundle.putString("OrderNo",txt_OrderNo.getText().toString());
                    paramBundle.putString("StyleNo",txt_StyleNo.getText().toString());
                    paramBundle.putString("StyleSort",txt_StyleSort.getText().toString());
                    paramBundle.putString("Size1",itemSize1.getText().toString());
                    paramBundle.putString("Size2",itemSize2.getText().toString());
                    paramBundle.putString("Size3",itemSize3.getText().toString());
                    paramBundle.putString("Size4",itemSize4.getText().toString());
                    paramBundle.putString("Size5",itemSize5.getText().toString());
                    paramBundle.putString("Size6",itemSize6.getText().toString());
                    paramBundle.putString("Size7",itemSize7.getText().toString());
                    paramBundle.putString("Size8",itemSize8.getText().toString());
                    paramBundle.putString("Size9",itemSize9.getText().toString());
                    paramBundle.putString("Size10",itemSize10.getText().toString());
                    paramBundle.putString("Size11",itemSize11.getText().toString());
                    paramBundle.putString("Size12",itemSize12.getText().toString());
                    paramBundle.putString("Size13",itemSize13.getText().toString());
                    paramBundle.putString("Size14",itemSize14.getText().toString());
                    paramBundle.putString("Size15",itemSize15.getText().toString());
                    intentPullActivity.putExtras(paramBundle);
                    startActivity(intentPullActivity);
                } else {
                    curToast.setText("请先搜索制单款号！");
                    curToast.show();
                }
                break;
            case R.id.btn_PullEdit:
                if ((curProduceCutMaID!=null)&&(curProduceCutMaID.length()>0)){
                    Intent intentPullActivity=new Intent(getContext(),PullActivity.class);
                    //简单参数通过Intent的Extras传递;
                    paramBundle.clear();
                    paramBundle.putString("LoginUserNo", curLoginUserNo);
                    paramBundle.putString("LoginUser",curLoginUser);
                    paramBundle.putString("CurDepartNo",curDepartNo);
                    paramBundle.putString("CurDepart",curDepart);
                    paramBundle.putString("ServiceUrl",curServiceUrl);
                    paramBundle.putString("ServiceDir",curServiceDir);
                    paramBundle.putString("CPUID",CPUID);
                    paramBundle.putString("ProduceCutMaID", curProduceCutMaID);
                    intentPullActivity.putExtras(paramBundle);
                    startActivity(intentPullActivity);
                } else {
                    curToast.setText("请先搜索制单款号并选择需编辑的床次！");
                    curToast.show();
                }
                break;
            case R.id.edt_SearchStyleNo:
                showIM(v);
                break;
            default:
                break;
        }
    }

    //刷新缸布列表;
    private void searchStyleNoData(String SearchParam)
    {
        String SqlComm="Exec KeyPoint_SearchStyleNo @SearchParam='" + SearchParam + "',@OPERTYPE='SEARCH',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }


    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = ToolUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    String OperType="";
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)){
                        if (jsonArray.optJSONObject(0).has("OperType")==true)  OperType=jsonArray.optJSONObject(0).getString("OperType");
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true)  OperType=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (OperType.equals("SCANBARCODE")) {
                            headJSON= jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_SCANBARCODE;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OperType.equals("DETAIL")) {
                            detailJSON=jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_DETAIL;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OperType.equals("CUTLIST")) {
                            cutlistJson=jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_CUTLIST;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OperType.equals("SEARCH")){
                            orderJSON=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_SEARCHOVER;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        };
        new Thread(run).start();

    }


    public  String TransValue(String params)
    {
        if (params.toUpperCase().equals("NULL")||params.equals("0")||params.equals("0.0"))
            return "";
        else return params;
    }


    //订单表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_a_listhead, null, false);
            int pullVatListWidth=parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(38)));
            int color = getResources().getColor(R.color.text_black);
            int fontSize=17;
            String tmpValue;
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                //控制是否需要显示对应的尺码;
                if (detailJSON.optJSONObject(position).has("ConColor")==true) {
                    tmpValue = detailJSON.optJSONObject(position).getString("ConColor").toString();
                    if (tmpValue.equals("1"))
                        color = getResources().getColor(R.color.text_blue);
                    if (tmpValue.equals("2"))
                        color = getResources().getColor(R.color.text_red);
                    if (tmpValue.equals("3"))
                        color = getResources().getColor(R.color.text_gray);
                    if (tmpValue.equals("0"))
                        color = getResources().getColor(R.color.text_black);
                }
                TextView tv = convertView.findViewById(R.id.txt_item_Color);// 显示文字
                if (detailJSON.optJSONObject(position).has("Color")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("Color").toString());
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
                tv =  convertView.findViewById(R.id.txt_item_ColorNo);// 显示文字
                if (detailJSON.optJSONObject(position).has("ColorNo")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("ColorNo").toString());
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
                tv =  convertView.findViewById(R.id.txt_item_Pertain);// 显示文字
                if (detailJSON.optJSONObject(position).has("Pertain")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("Pertain").toString());
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
                tv = convertView.findViewById(R.id.txt_item_Size1);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size1")==true)
                    tv.setText(TransValue(detailJSON.optJSONObject(position).get("Size1").toString()));
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
                tv = convertView.findViewById(R.id.txt_item_Size2);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size2")==true)
                    tv.setText(TransValue(detailJSON.optJSONObject(position).get("Size2").toString()));
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
                tv =  convertView.findViewById(R.id.txt_item_Size3);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size3")==true)
                    tv.setText(TransValue(detailJSON.optJSONObject(position).get("Size3").toString()));
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
                tv = convertView.findViewById(R.id.txt_item_Size4);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size4")==true)
                    tv.setText(TransValue(detailJSON.optJSONObject(position).get("Size4").toString()));
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
                tv = convertView.findViewById(R.id.txt_item_Size5);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size5")==true)
                    tv.setText(TransValue(detailJSON.optJSONObject(position).get("Size5").toString()));
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
                tv =  convertView.findViewById(R.id.txt_item_Size6);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size6")==true)
                    tv.setText(TransValue(detailJSON.optJSONObject(position).get("Size6").toString()));
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
                tv =  convertView.findViewById(R.id.txt_item_Size7);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size7")==true)
                    tv.setText(TransValue(detailJSON.optJSONObject(position).get("Size7").toString()));
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
                tv =  convertView.findViewById(R.id.txt_item_Size8);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size8")==true)
                    tv.setText(TransValue(detailJSON.optJSONObject(position).get("Size8").toString()));
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
                tv =  convertView.findViewById(R.id.txt_item_Size9);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size9")==true)
                    tv.setText(TransValue(detailJSON.optJSONObject(position).get("Size9").toString()));
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
                tv =  convertView.findViewById(R.id.txt_item_Size10);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size10")==true)
                    tv.setText(TransValue(detailJSON.optJSONObject(position).get("Size10").toString()));
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
                tv = convertView.findViewById(R.id.txt_item_Size11);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size11")==true)
                    tv.setText(TransValue(detailJSON.optJSONObject(position).get("Size11").toString()));
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
                tv = convertView.findViewById(R.id.txt_item_Size12);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size12")==true)
                    tv.setText(TransValue(detailJSON.optJSONObject(position).get("Size12").toString()));
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
                tv = convertView.findViewById(R.id.txt_item_Size13);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size13")==true)
                    tv.setText(TransValue(detailJSON.optJSONObject(position).get("Size13").toString()));
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
                tv = convertView.findViewById(R.id.txt_item_Size14);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size14")==true)
                    tv.setText(TransValue(detailJSON.optJSONObject(position).get("Size14").toString()));
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
                tv = convertView.findViewById(R.id.txt_item_Size15);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size15")==true)
                    tv.setText(TransValue(detailJSON.optJSONObject(position).get("Size15").toString()));
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
                tv = convertView.findViewById(R.id.txt_item_TotalPiece);// 显示文字
                if (detailJSON.optJSONObject(position).has("TotalPiece")==true)
                    tv.setText(TransValue(detailJSON.optJSONObject(position).get("TotalPiece").toString()));
                tv.setTextColor(color);
                tv.setTextSize(fontSize);
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","MarkListAdapter_position:"+position);
            return convertView;
        }
    }

    //订单表格适配器;
    public final class CutListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public CutListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return cutlistJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return cutlistJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_a_cutlisthead, null, false);
            int pullVatListWidth=parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(38)));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                //控制是否需要显示对应的尺码;
                if (cutlistJson.optJSONObject(position).has("ConColor")==true) {
                    tmpValue = cutlistJson.optJSONObject(position).getString("ConColor").toString();
                    if (tmpValue.equals("1"))
                        color = getResources().getColor(R.color.text_blue);
                    if (tmpValue.equals("2"))
                        color = getResources().getColor(R.color.text_red);
                    if (tmpValue.equals("3"))
                        color = getResources().getColor(R.color.text_gray);
                    if (tmpValue.equals("0"))
                        color = getResources().getColor(R.color.text_black);
                }
                TextView tv = convertView.findViewById(R.id.txt_item_CutDate);// 显示文字
                if (cutlistJson.optJSONObject(position).has("CutDate")==true)
                    tv.setText(cutlistJson.optJSONObject(position).get("CutDate").toString());
                tv.setTextColor(color);
                tv =  convertView.findViewById(R.id.txt_item_CutInv);// 显示文字
                if (cutlistJson.optJSONObject(position).has("CutInv")==true)
                    tv.setText(TransValue(cutlistJson.optJSONObject(position).get("CutInv").toString()));
                tv.setTextColor(color);
                tv =  convertView.findViewById(R.id.txt_item_BedNo);// 显示文字
                if (cutlistJson.optJSONObject(position).has("BedNo")==true)
                    tv.setText(TransValue(cutlistJson.optJSONObject(position).get("BedNo").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.txt_item_LevelNum);// 显示文字
                if (cutlistJson.optJSONObject(position).has("LevelNum")==true)
                    tv.setText(TransValue(cutlistJson.optJSONObject(position).get("LevelNum").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.txt_item_Number);// 显示文字
                if (cutlistJson.optJSONObject(position).has("Number")==true)
                    tv.setText(TransValue(cutlistJson.optJSONObject(position).get("Number").toString()));
                tv.setTextColor(color);

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","CutListAdapter_position:"+position);
            return convertView;
        }
    }

    //清除界面显示内容
    private void clearFormText(){
        txt_HintInfo.setText("");
        txt_OrderNo.setText("");
        txt_StyleNo.setText("");
        txt_StyleSort.setText("");
        txt_HintInfo.setText("");
    }

    //填充界面显示内容;
    private void fillFormtext(JSONObject jsonObject){
        try {
            if (jsonObject.has("ProduceMasterID")==true) curProduceMasterID=jsonObject.getString("ProduceMasterID");
            if (jsonObject.has("OrderNo")==true) txt_OrderNo.setText(jsonObject.getString("OrderNo"));
            if (jsonObject.has("StyleNo")==true) txt_StyleNo.setText(jsonObject.getString("StyleNo"));
            if (jsonObject.has("StyleSort")==true) txt_StyleSort.setText(jsonObject.getString("StyleSort"));
            if (jsonObject.has("HintInfo")==true) txt_HintInfo.setText(jsonObject.getString("HintInfo"));
            if (jsonObject.has("Size1")==true) itemSize1.setText(jsonObject.getString("Size1"));else itemSize1.setText("--");
            if (jsonObject.has("Size2")==true) itemSize2.setText(jsonObject.getString("Size2"));else itemSize2.setText("--");
            if (jsonObject.has("Size3")==true) itemSize3.setText(jsonObject.getString("Size3"));else itemSize3.setText("--");
            if (jsonObject.has("Size4")==true) itemSize4.setText(jsonObject.getString("Size4"));else itemSize4.setText("--");
            if (jsonObject.has("Size5")==true) itemSize5.setText(jsonObject.getString("Size5"));else itemSize5.setText("--");
            if (jsonObject.has("Size6")==true) itemSize6.setText(jsonObject.getString("Size6"));else itemSize6.setText("--");
            if (jsonObject.has("Size7")==true) itemSize7.setText(jsonObject.getString("Size7"));else itemSize7.setText("--");
            if (jsonObject.has("Size8")==true) itemSize8.setText(jsonObject.getString("Size8"));else itemSize8.setText("--");
            if (jsonObject.has("Size9")==true) itemSize9.setText(jsonObject.getString("Size9"));else itemSize9.setText("--");
            if (jsonObject.has("Size10")==true) itemSize10.setText(jsonObject.getString("Size10"));else itemSize10.setText("--");
            if (jsonObject.has("Size11")==true) itemSize11.setText(jsonObject.getString("Size11"));else itemSize11.setText("--");
            if (jsonObject.has("Size12")==true) itemSize12.setText(jsonObject.getString("Size12"));else itemSize12.setText("--");
            if (jsonObject.has("Size13")==true) itemSize13.setText(jsonObject.getString("Size13"));else itemSize13.setText("--");
            if (jsonObject.has("Size14")==true) itemSize14.setText(jsonObject.getString("Size14"));else itemSize14.setText("--");
            if (jsonObject.has("Size15")==true) itemSize15.setText(jsonObject.getString("Size15"));else itemSize15.setText("--");
            if (jsonObject.has("ErrInfo")==true)
            {
                AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                        .setTitle("系统提示").setMessage(headJSON.getJSONObject(0).getString("ErrInfo"))
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                return;
                            }
                        }).create(); // 创建对话框
                alertDialog.show(); // 显示对话框
            }
            if (txt_StyleNo.getText().length()>0) queryDetailData(curProduceMasterID);

        } catch (JSONException e) {
            e.printStackTrace();
        }


    }




    @Override
    public void onStart() {
        super.onStart();
        //设置焦点
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.Start");
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.End");
    }
}
